import axios from "axios";
import store from './store'
import router from "./router";
import Element from "element-ui"

//在开发环境
// axios.defaults.baseURL = "http://localhost:62475"
axios.defaults.baseURL = "http://localhost:5000"
//在生产环境
// axios.defaults.baseURL = "http://39.108.62.250:9005"

const request = axios.create({
	timeout: 5000,
	headers: {
		'Content-Type': "application/json; charset=utf-8"
	}
})

request.interceptors.request.use(config => {
	config.headers['Authorization'] = localStorage.getItem("token")	// 请求头带上token
	return config
})

// 重试队列，每一项将是一个待执行的函数形式
let requests = [];

request.interceptors.response.use(response => {
		// console.log("response ->" + response)

		let res = response.data
		// console.log(res)
		// console.log(response.config);

		if (res.code === 200) {
			return response
		}else if(res.code === 401){
			router.push("/login")
			return Promise.reject(response.data.msg)
		} else {
			Element.Message.error(!res.msg ? '系统异常' : res.msg)
			return Promise.reject(response.data.msg)
		}
	},
	error => {
		//http出现非200状态码进入
		// console.log(error)
		let res = error.response.data
		// console.log(error.response.data)
		// console.log(error.response.config.url)
		// 获取当前失败的请求
		const config = error.response.config

		if (error.response.data) {
			error.massage = error.response.data.msg
		}
		//如果是401未登录没权限的就调到登录页面，其他的就直接弹窗显示错误。 
		if (error.response.status === 401) {
			if(res.msg == "更新Token"){
				var jwt = res.data;
				store.commit('SET_TOKEN', jwt);
				// 更新token
				config.headers['Authorization'] = localStorage.getItem("token");
				// 再次请求
				requests.forEach(cb => cb(jwt));
				requests = [];
				return request(config);
			}
			if(res.msg == "正在更新Token"){
				// console.log("等待更新执行");
				// 正在刷新token，将返回一个未执行resolve的promise
				return new Promise((resolve) => {
					// 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
					requests.push((token) => {
						// console.log("执行")
						config.headers['Authorization'] = token;
						resolve(request(config));
					});
				});
			}
			router.push("/login")
		}
		Element.Message.error(error.massage, {duration: 3000})
		return Promise.reject(error)
	}
)

export default request